package com.mworld.galaxy.bull.service.account;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.mworld.galaxy.bull.entity.MemberUser;
import com.mworld.galaxy.bull.repository.MemberUserDao;
import com.mworld.galaxy.bull.service.ServiceException;

/**
 * 用户管理类.
 * 
 * @author michael
 */
// Spring Service Bean的标识.
@Component
@Transactional(readOnly = true)
public class MemberAccountService extends AccountService {

    @Autowired
    private MemberUserDao memberUserDao;

    @Override
    public List<MemberUser> getAllUser() {
        List<MemberUser> users = (List<MemberUser>) memberUserDao.findAll();
        return users;
    }

    @Override
    public MemberUser getUser(Long id) {
        MemberUser user = memberUserDao.findOne(id);
        return user;
    }

    @Override
    public MemberUser findUserByLoginName(String loginName) {
        MemberUser user = memberUserDao.findByLoginName(loginName);
        return user;
    }

    @Transactional(readOnly = false)
    public void registerUser(MemberUser user) {
        entryptPassword(user);
        user.setRoles("member");
        user.setRegisterDate(dateProvider.getDate());

        memberUserDao.save(user);
    }

    @Transactional(readOnly = false)
    public void updateUser(MemberUser user) {
        if (StringUtils.isNotBlank(user.getPlainPassword())) {
            entryptPassword(user);
        }
        memberUserDao.save(user);
    }

    @Override
    @Transactional(readOnly = false)
    public void deleteUser(Long id) {
        if (isSupervisor(id)) {
            logger.warn("操作员{}尝试删除超级管理员用户", getCurrentUserName());
            throw new ServiceException("不能删除超级管理员用户");
        }
        memberUserDao.delete(id);
    }
}
